#!/usr/bin/env node

const { program } = require('commander');
const path = require('path');
const pkg = require('./package');
var mqtt = require('mqtt')
var jsome = require('jsome');

program
.version(pkg.version)
.option('-p,--path [value]','Request File Path')
.parse(process.argv);

const options = program.opts();

if(options.path) {
    let req_file_path = path.isAbsolute(options.path) ? options.path : path.join(__dirname,options.path);
    let req_content = require(req_file_path);

    var client  = mqtt.connect('mqtt://192.168.2.24:31883')

    client.on('connect', function () {
        client.subscribe(req_content.subscriber_topic, function (err) {
            if (!err) {
                client.publish(req_content.publish_topic, JSON.stringify(req_content.data));
            }
        })
    })

    client.on('message', function (topic, message) {
        // message is Buffer
        console.log("Receive Topic:", topic, "\n");
        jsome.parse(message.toString());
        //client.end()
    });
}